"use strict";

Array.prototype.getLast=function(){
	return this[this.length-1];
}
Date.prototype.getString=function(s){
	console.log(this.toJSON())
	s=s||"-"
	return this.getFullYear()+s+(this.getMonth()+1)+s+this.getDate()+" "+this.getHours()+":"+((this.getMinutes()<10)?"0"+this.getMinutes():this.getMinutes());
}
Date.prototype.getMonthDay=function(vote){
	console.log(new Date(this.getFullYear(),this.getMonth()+1,0)-86400000)
	let a=new Date(this.getFullYear(),this.getMonth()+1,0).getTime();
	return vote?new Date(a):new Date(a).getDate();
}
Date.prototype.getMD=function(){
	return this.getJSON().substring(5);
}
Date.prototype.getWD=function(){
	switch(this.getDay()){
		case 0:
		return "星期日";
		case 1:
		return "星期一";
		case 2:
		return "星期二";
		case 3:
		return "星期三";
		case 4:
		return "星期四";
		case 5:
		return "星期五";
		case 6:
		return "星期六";
	}
}
Date.prototype.getCMD=function(){
	return (this.getMonth()+1)+"月"+this.getDate()+"日";
}
Date.prototype.getJSON=function(){
	return `${this.getFullYear()}-${(this.getMonth()+1)<10?`0${(this.getMonth()+1)}`:(this.getMonth()+1)}-${this.getDate()<10?`0${this.getDate()}`:this.getDate()}`;
}
$.fn.extend({
	setBodyPaddingBottom:function(num){
		num=num||0;		
		var oldpd=$("body").css("padding-bottom").getFloat();
		console.log(this.outerHeight(true))
		$("body").css({
			"padding-bottom":this.outerHeight(true)+oldpd+num
		})
	},
	fileImg:function(d){
		if(!this.is("input[type=file][filtype=img]"))return;
		console.log(d,1111)
		d=d||this.siblings().find("img");
		d[0].onload=function(){
			d.siblings(".il-box").css({
				display:"none"
			})
		}
		this.on("change",function(){
			console.log(this)
			var that=this;
			var imgobj=this.files[0];
			d.siblings(".il-box").css({
				display:"inline-block"
			})
			if (this.files[0].size/1024>5120) {
				alert("图片不能大于5M!");
				this.value="";
				d.siblings(".il-box").css({
					display:"none"
				})
				return ;
			}
			var fileRead=new FileReader();
	      	fileRead.readAsDataURL(imgobj);
			fileRead.onload=function(e){

				d.attr("src",this.result);
				d.addClass("disblock");
			}
		})
	},
	setTextVal:function(data){
		console.log(data)
		if (!this.is("form")) {console.error("类型不匹配！");return;}
		for(var i=0;i<this[0].length;i++){
			if(data[$(this[0][i]).attr("name")]){
				if ($(this[0][i]).attr("setdata")) {
					if (typeof window[$(this[0][i]).attr("setdata")]=="function") {
						window[$(this[0][i]).attr("setdata")](data[$(this[0][i]).attr("name")]?data[$(this[0][i]).attr("name")].split(','):[]);
					}else if(typeof window[$(this[0][i]).attr("setdata")]=="object"&&window[$(this[0][i]).attr("setdata")]["setData"]){
						console.log(data[$(this[0][i]).attr("name")]);
						let datas='';
						try{
							datas=data[$(this[0][i]).attr("name")].split(',');
						}catch(e){
							datas=[data[$(this[0][i]).attr("name")]]
						}
						window[$(this[0][i]).attr("setdata")]["setData"](datas);
					}else{
						console.error("setData函数未定义！");
					}
					//$(this[0][i]).setData
				}else{
					if($(this[0][i]).is("[type=text],textarea")){
						console.log($(this[0][i]))
						if(data[$(this[0][i]).attr("name")]){
							$(this[0][i]).val(data[$(this[0][i]).attr("name")]);
						}
					}else
					if ($(this[0][i]).is(`[type=checkbox][value="${data[$(this[0][i]).attr("name")]}"]`)) {
						$(this[0][i]).prop("checked",true);
					} 
				}	
			}
			
		}
	},
	wordRotation:function(text,speed=10){
		let dom=$(`<div>${text}</div>`);
		this.append(dom);
		if (!/absolute|relative|fixed/.test($(this).css("position"))) {
			this.css({"position":"relative"});
		}
		this.css({
			overflow:"hidden",

		})
		dom.width(dom.width()+20)
		let _b_w=this.width();
		let _c_w=dom.width();
		let _pos=_b_w+_c_w;
		let i=_pos,
			times=setInterval(gd,speed);
		dom.css({
			"position":"absolute",
			left:_b_w
		})
		this.hover(function(){
			clearInterval(times)
		},function(){
			times=setInterval(gd,speed);
		})

		function gd(){
			dom.css({
				left:i
			})
			i=i<-_c_w?_b_w:i-1;
		}
	}

})
String.prototype.getFloat=function(){
	return parseFloat(this.replace(/[^(\d|\.)]/g,""));
}
/*统一事件*/
$("button[for=formdom]").on("click",function(e){
	if ($(this).attr("cabel")=="no") {console.log("false");return;}
	if ($(this).attr("eventfu")&&!$(this).attr("skip")) {
		if(!window[$(this).attr("eventfu")](e,this)){
			return ;
		}
	}else{
		$(this).removeAttr("skip");
	}
	if ($(this).attr("cabel")=="confirm") {
		if (!confirm($(this).attr("msg"))) {
			return;
		}
	}

	var that=$("form#formdom"),those=$(this);
	formAjax($("form#formdom"),(function(es){
		if (!es) {
			return false;
		} 
		return function(d){
			location.href=es;
		};
	})(those.attr("rurl"))||window[$("form#formdom").attr("success")]||function(d){
		if(those.attr("rurl")||that.attr("rurl")){
			location.href=that.attr("rurl");
		}
	})
	$(this).removeAttr("skip");
})
/*工具函数*/
function getUrlParameter(key){
	var s=location.search.substring(1,location.search.length);

	var arr=s.split("&");
	var res={};
	//	console.log(arr)

	for(var i of arr){
	//	console.log(i)
	/*	if (typeof arr[i]!="String") {
			continue;
		}*/
		var d=i.split("=");
		if (d[0]==key) {return d[1];};
		res[d[0]]=d[1];
	}
	return key?"":res;
}
function getStorage(t){
	var arr={};
	for(var i in localStorage){
		if (i=="length") {break;}
		if (i==t) {
			return localStorage[i];
		}
		arr[i] = localStorage[i];
	}
	//if (t=="uid") {return 9527;}
	//if (t=="token") {return "af75607fdfff40d0a9a09f3c51263889";}
	return t?"":arr;
}
function setStorage(k,v){
	localStorage.setItem(k,v);
}
function removeStorage(k){
	localStorage.removeItem(k);
}
function appendCID(d){
	d.append("carrentId",CID);
}
function toDom(d){
	switch(d.constructor.name){
		case "String":
		return $(d);
		case "jQuery":
		return d;
		default:
		console.error("参数错误！仅限jQuery对象或jQuery选择器！");
		return false;
	}
}
function getLocation(call,error)
  {
  	try{
  		var getlocation=new  AMap.Geolocation({
			enableHighAccuracy:true,
			timeout:10000,
			convert:true,
			showButton:true,
			zoomToAccuracy:true,
			showMarker:false,
			showCircle:false,
		})
		//maps.addControl(getlocation);
		console.log("ddd")
		getlocation.getCurrentPosition()
		  AMap.event.addListener(getlocation, 'complete', onComplete)
		  AMap.event.addListener(getlocation, 'error', error||onError)

		  function onComplete (data) {
		    // data是具体的定位信息
		    console.log(data)
		    call(data)
		   
		  }
		  function onError (data) {
		    console.log(data)
		    alert("定位失败！")
		    // 定位出错
		  }
		}catch(e){
			setTimeout(function(){
				getLocation(call,error);
			},1000)
		}
 
  }
function mbmove(){
	
}
function setsStroge(k,v){
	if (typeof k=="string") {
		sessionStorage.setItem(k,v);
	}else
	if(typeof k=="object"){
		for(let i in k){
			sessionStorage.setItem(i,k[i]);
		}
	}
}
function getsStroge(k){
	let res={};
	let s=sessionStorage;
	for(let i=0;i<s.length;i++){
		if (k&&k==s.key(i)) {
			return s.getItem(s.key(i));
		}else{
			res[s.key(i)]=s.getItem(s.key(i));
		}
	}
	return k?false:res;
}
function ssremove(k){
	sessionStorage.removeItem(k);
}









function Analog(opt){
	this.option={
		type:'checkbox',/*模拟框样式： checkbox*/
		ishead:false,/*是否需要头部*/
		content:[/*弹出框内容 数组，jQuery文本对象，html字符串*/
		
		],
		autovalue:true,
		isyes:true,
		position:0,
		cdom:"",/*"[name=crdType]",*//*触发open对象*/
		opentype:'bottom',/*打开方式 bottom 底部向上划出，right 右边划出*/
		autoClose:true
	}
	for(var i in opt){
		this.option[i]=opt[i];
	}
	var that=this;
	domload();
	function domload(){
		let domstr=``,box=$(`<div class="Analog ${that.option.type=="alert"?"Analog-alert":""} ${that.option._bclass||""} Analog-hide-${that.option.opentype}">
			${that.option.ishead?`<div class="Analog-head">
				<i></i>
				${that.option.title?`<h2>${that.option.title}</h2>`:""}
				${that.option.isyes?'<p>确定</p>':""}
			</div>`:""}
			<div class="Analog-content">
			</div>
		</div>`);
		console.log(toDom(that.option.cdom).outerHeight(true))
		if (that.option.zoom) {
			box.css({
				"z-index":that.option.zoom
			})
		}
		if (that.option.ishead) {
			box.css({
				"padding-top":"0.98rem"
			})
		}
		if (that.option.opentype=="after") {
			console.log(toDom(that.option.cdom).offset().top+10)
			box.css({
				position:"absolute",
				top:toDom(that.option.cdom).offset().top+toDom(that.option.cdom).outerHeight(true)+10,
				left:0,

			})
		}else{
			console.log(that.option.position[0],that.option.position[1])
			box.css({
				left:that.option.position[0],
				top:that.option.position[1]
			})
			
		}
		$("body").append(box);

		that.dom=box;

		box.find(".Analog-head i,.Analog-head p").on("click",function(){
			that.closeType=$(this).is("p");
			that.close();
		})

		switch(that.option.content.constructor.name){
			case "Array":
				let arr=that.option.content;
				for(var i of arr){
					domstr+=`
						<div class="form-analog-check">
							<input form="${i.form||""}" value='${i.value}' type="${i.type}" name="${i.name}" id="${i.name}${i.value}">
							<label for="${i.name}${i.value}">${i.text}</label>
						</div>
					`;
					box.find(".Analog-content").html(domstr);
				}
			break;
			case "jQuery":
				box.find(".Analog-content").append(that.option.content);
			break;
			case "String":
				box.find(".Analog-content").html(that.option.content);
			break;
			default:
			return false;
		}
		if (that.option.opentype=="bottom") {
			box.css("bottom",-box.outerHeight(true));
		}
		toDom(that.option.cdom).on("click",function(){
			console.log("Analog open!");
			that.open();
		})
		if (that.option.autoClose) {
			$(document).on("click",function(e){
				if (that.openVote&&(!$(e.target).is(box)&&!$(e.target).parents(".Analog").is(box)&&!($(e.target).is(toDom(that.option.cdom))||$(e.target).parents().is(toDom(that.option.cdom))))) {
					that.close();
				}
			})
		}
		box.find("input[type=radio]").on("change",function(){
			if (that.openVote&&that.option.autoClose) {
				that.close();
				/*if (toDom(that.option.cdom).is("input[type=button]")) {
					autovalue
				}*/
			}
		})
	}
}
Analog.prototype.open=function(){
	this.dom.addClass("Analog-open");
	$("html,body").css({
		overflow: "hidden"
	})
	this.openVote=true;
	if (this.option.openCall) {
		this.option.openCall(this);
	}
}
Analog.prototype.setData=function(data){
	if (!data) {return;}
	var that=this;
	data=data||that.option.setData;
	if (toDom(that.option.cdom).is("input")) {
		if (data.constructor.name=="Array"||data.constructor.name=="Number") {
			if (data.constructor.name=="Number") {
				data=[data];
			}
			for(var i of data){
				console.log(i)
				if(!i){
					continue;
				}
				that.dom.find(`input[value='${i}']`).prop("checked",true);
				
			}
			that.close();
		}
	}
}
Analog.prototype.close=function(){
	this.dom.removeClass("Analog-open");
	$("html,body").css({
		overflow: "scroll"
	})
	if (this.option.closeCall) {
		this.option.closeCall(this);
	}
	this.openVote=false;
	console.log("Analog close!");
	if (this.option.autovalue) {
		console.log("dddddd")
		this.autovalue();
	}
}
Analog.prototype.autovalue=function(){
	let a=[],b=[];
	for(var i=0;i<this.dom.find("input:checked").length;i++){
		a.push(this.dom.find("input:checked").eq(i).val());
		b.push(this.dom.find("input:checked+label").eq(i).text());
	}
	toDom(this.option.cdom).attr("val",a.join(","));
	toDom(this.option.cdom).val(b.join(" "));
}
Analog.prototype.setTit=function(t){
	console.log(t)
	this.dom.find(".Analog-head h2").html(t);
}
function getdistance(a){
	console.log(a)
	if (!a[0]||!a[1]) {
		return 0;
	}
	a[0]=parseFloat(a[0]);
	a[1]=parseFloat(a[1]);

	let b=[getStorage("_lng"),getStorage("_lat")];
	b[0]=parseFloat(b[0]);
	b[1]=parseFloat(b[1]);
	let dis=AMap.GeometryUtil.distance(a,b)
	
	return Math.round(dis);

}
function locaset(){
    var locaan=new Analog({
        cdom:".head-loca",
        content:`
        <div class="city-box">
            <div class="city-search">
				<span>
					<input type="text" id="city-search-text" placeholder="城市名称" />
					<button id="city-search-text"></button>
				</span>
            </div>
            <div class="city-cont">
                <div class="city-screen">
                </div>
                <div class="city-libox" id="city-loca">
                    <p>当前定位城市</p>
                    <div>
                       <span>
                            <input type="radio" name="city-list" val="" id="cloca"/>
                            <label for="cloca">定位中...</label>
                       </span>
                    </div>
                </div>
                <div class="city-screen">
					${cityscreen()}
                </div>
                 <div class="city-libox city-list">
                        ${citylistload()}
                </div>
            </div>
        </div>
            `,
        opentype:"right",
        title:"选择城市",
        ishead:true,
        isyes:false,
        autoClose:false,
        autovalue:false,
        closeCall:function(d){
            /*setStorage("_lat",$("[name=city-list]:checked").val().split(",")[1]);
            setStorage("_lng",$("[name=city-list]:checked").val().split(",")[0]);*/
        }

    })
    function citysearchfun(letter){
    	let arr=[];
    	for(let j of lv2BasicsData){
    		if(j.name.search(letter)!=-1){
    			arr.push(j);
    		}
    	}
    	let str=`<p>${letter}</p><div>`;
	    for(let i of arr){
	        str+=` <span>
	                    <input type="radio" name="city-list" value="" id="clist-${i.code}"/>
	                    <label for="clist-${i.code}">${i.name}${""/*i.name!="祁连县"?` (暂未开放,敬请期待)`:""*/}</label>
	               </span>`;
	    }
	    return str+"</div>";
    }
    $("#city-search-text").on("input",function(){
    	console.log($(this).val())
    	$(".city-list").html(citysearchfun($(this).val()));
    })
 /*  var  mapObj = new AMap.Map('map');
	mapObj.plugin('AMap.Geolocation', function () {
		console.log(mapObj)
    var geolocation = new AMap.Geolocation({
       enableHighAccuracy:true,
		timeout:10000,
		convert:true,
		showButton:true,
		zoomToAccuracy:true,
		showMarker:false,
		showCircle:false,
		noGeoLocation:3,
    });
    mapObj.addControl(geolocation);
    geolocation.getCurrentPosition();
    AMap.event.addListener(geolocation, 'complete', function(result) {
        	console.log(result)
        	//alert(result.formattedAddress)
            if (result.info === "SUCCESS"&&result.addressComponent) {
               $("#cloca").val(result.addressComponent.city||result.addressComponent.province);
               $(`[for="cloca"]`).text(result.addressComponent.city||result.addressComponent.province);
               if (!$("[name='city-list']:checked").length) {
               		$("#cloca").prop("checked",true);
               		$("[name=city-list]:checked").trigger("change");
               }
            } else {
                $("#cloca").attr("disabled","disabled")
               $(`[for="cloca"]`).text("定位失败")
            }
        });//返回定位信息
    AMap.event.addListener(geolocation, 'error', function(e){
    	console.log(e)

    });      //返回定位出错信息
});*/
	if (window.__wxjs_environment === 'miniprogram') {
			wxlocation();
		}else{
			iplocation();
		}
	function wxlocation(){
		wx.ready(function(){
				wx.getLocation({
					type:"gcj02",
					success:function(d){
						try{
						var latitude = d.latitude; // 纬度，浮点数，范围为90 ~ -90
						var longitude = d.longitude; // 经度，浮点数，范围为180 ~ -180。
						lnglatToAddress([longitude,latitude])
					}catch(e){
						alert_copy(e)
					}
					},
					fail:function(){
						iplocation();
					}
				})
			})
	}
    function iplocation(){
    	var citysearch = new AMap.CitySearch();
        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity(function(status, result) {
        	console.log(status,result,$("[name='city-list']:checked").length)
            if (status === 'complete' && result.info === 'OK') {
               $("#cloca").val(result.city);
               $(`[for="cloca"]`).text(result.city);
               if (!$("[name='city-list']:checked").length) {
               		$("#cloca").prop("checked",true);
               		$("[name=city-list]:checked").trigger("change");
               }
            } else {
                $("#cloca").attr("disabled","disabled")
               $(`[for="cloca"]`).text("定位失败")
            }
        });
    }
    function lnglatToAddress(e){
			var loca=(typeof e=="Array")?new AMap.LngLat(e[0],e[1]):e;
			var geoc=new AMap.Geocoder({
				radius:1000,
				extensions:"all"
			})
			geoc.getAddress(e,function(m,d){
				var data=d.regeocode;
				console.log(m,d)
			    try{
			    	if (m === 'complete' && d.info === 'OK') {
		               $("#cloca").val(data.addressComponent.city||data.addressComponent.province);
		               $(`[for="cloca"]`).text(data.addressComponent.city||data.addressComponent.province);
		               if (!$("[name='city-list']:checked").length) {
		               		$("#cloca").prop("checked",true);
		               		$("[name=city-list]:checked").trigger("change");
		               }
		            } else {
		                $("#cloca").attr("disabled","disabled")
		               $(`[for="cloca"]`).text("定位失败")
		            }
			    }catch(e){
			    	alert_copy(e)
			    }
			    
			});
		}
    $(".city-screen input").on("change",function(){
        $(".city-list").html(citylistload(this.value));
    })
    $(".city-box").on("change","[name=city-list]",function(){
       $(".head-loca").text($(`[for='${$(this).attr("id")}']`).text().split(",")[0]);
        locaan.close();
    })
}

function cityscreen(){
    let str=``;
    for(let i=65;i<=90;i++){
        str+=`
             <span>
                <input type="radio" name="city-screen" ${i==65?"checked='checked'":""} value="${String.fromCharCode(i)}"  id="cs-${String.fromCharCode(i)}"/>
                <label for="cs-${String.fromCharCode(i)}">${String.fromCharCode(i)}</label>
            </span>
        `
    }
    return str;
}
function citylistload(letter){
    letter=letter||"A";
    let str=`<p>${letter}</p><div>`;
    for(let i of lv2Letter[letter]){
        str+=` <span>
                    <input type="radio" name="city-list" value="" id="clist-${i.code}"/>
                    <label for="clist-${i.code}">${i.name}${""/*i.name!="祁连县"?` (暂未开放,敬请期待)`:""*/}</label>
               </span>`;
    }
    return str+"</div>";
}
 function setconfig(d){
     wx.config({
            debug:false,
            appId:"wxce4b505fed74074b",//"wx8003ce08a24d0fe9",
            timestamp:d.timestamp,
            nonceStr:d.nonce_str,
            signature:d.sign,
            jsApiList:["chooseImage","getLocalImgData","getLocation"]
           })
          

             wx.error(function(res){
              //  alert(res);
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
    });
}
function dataURLtoFile(dataurl, filename) {
  //  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
   let bstr = atob(dataurl), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename);
}
function getFileName(){
	return location.pathname.split(/\/|\./)[location.pathname.split(/\/|\./).length-2];
}
/*(function(d){
	console.log(d)
	window.alert_copy=window.alert;
	window.alert=function(s){
		if ($(".window-alert").length) {
			$(".window-alert").removeClass("window-alert-close");
			$(".window-alert .wa-cont").text(s);
		}else{
			let str=`
				<div class="window-alert">
					<div class="wa-box">
						<div class="wa-cont">${s}</div>
						<div class="wa-close">确定</div>
					</div>
					
				</div>
			`
			str=$(str);
			str.find(".wa-close").on("click",function(){
				str.addClass("window-alert-close");
			})
			$("body").append(str);
		}
	}
})(window.alert);*/
function dataHandle(data){	
	console.log(data)
	if (typeof data==="FormData") {
		data.append("userid",getUrlParameter("hd_id"))
		data.append("token",getStorage("hd_token"))
	}else{
		data.userid=getUrlParameter("hd_id");
		data.token=getStorage("hd_token");
	}
}